package com.example.appointment.repository;

import com.example.appointment.entity.Appointment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.List;

public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
    
    // 查询指定医生在某个时间段的预约
    @Query("SELECT a FROM Appointment a WHERE a.doctor.id = :doctorId " +
           "AND a.appointmentTime BETWEEN :startTime AND :endTime " +
           "AND a.status NOT IN ('CANCELLED')")
    List<Appointment> findByDoctorAndTimeRange(
        @Param("doctorId") Long doctorId,
        @Param("startTime") LocalDateTime startTime,
        @Param("endTime") LocalDateTime endTime
    );

    // 查询指定患者在某个时间段的预约
    @Query("SELECT a FROM Appointment a WHERE a.patient.id = :patientId " +
           "AND a.appointmentTime BETWEEN :startTime AND :endTime " +
           "AND a.status NOT IN ('CANCELLED')")
    List<Appointment> findByPatientAndTimeRange(
        @Param("patientId") Long patientId,
        @Param("startTime") LocalDateTime startTime,
        @Param("endTime") LocalDateTime endTime
    );

    // 查询患者的预约记录
    Page<Appointment> findByPatientIdOrderByAppointmentTimeDesc(Long patientId, Pageable pageable);

    // 查询医生的预约记录
    Page<Appointment> findByDoctorIdOrderByAppointmentTimeDesc(Long doctorId, Pageable pageable);

    // 查询科室的预约记录
    Page<Appointment> findByDepartmentIdOrderByAppointmentTimeDesc(Long departmentId, Pageable pageable);

    // 查询当天的预约数量
    @Query("SELECT COUNT(a) FROM Appointment a WHERE DATE(a.appointmentTime) = CURRENT_DATE " +
           "AND a.status NOT IN ('CANCELLED')")
    Long countTodayAppointments();

    // 根据医生ID和日期筛选预约（可选状态筛选）
    @Query("SELECT a FROM Appointment a WHERE a.doctor.id = :doctorId " +
           "AND (:date IS NULL OR DATE(a.appointmentTime) = :date) " +
           "AND (:status IS NULL OR a.status = :status) " +
           "ORDER BY a.appointmentTime DESC")
    Page<Appointment> findByDoctorIdAndDateAndStatus(
        @Param("doctorId") Long doctorId,
        @Param("date") LocalDate date,
        @Param("status") String status,
        Pageable pageable
    );
} 